package com.ellecity06.cwhiskymall.helper

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.MediaStore
import android.text.TextUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.ellecity06.common.ktx.stringResToString
import com.ellecity06.common.utils.*
import com.ellecity06.common.utils.BitmapUtils.Companion.bmpToByteArray
import com.ellecity06.cwhiskymall.BuildConfig
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.helper.ShareHelper.Companion.WECHAT_APPID_OUR
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXImageObject
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXVideoObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory

/**
 * @author ellecity06
 * @time 2024/11/4 11:23
 * @des
 */
val wxApi: IWXAPI by lazy { WXAPIFactory.createWXAPI(appContext, WECHAT_APPID_OUR) }

class ShareHelper {

    companion object {
        /**
         *
         */
        const val WECHAT_APPID_OUR = "wx257f402dd8e5cb5f"

        private val miniProgramType =
            if (BuildConfig.SERVER_RELEASE) WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE else WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW

        /**
         * 跳转微信小程序
         */
        fun goWeChatApplet(url: String, name: String) {
            if (!wxApi.isWXAppInstalled) {
                ToastUtils.show(R.string.text_please_install_wechat.stringResToString())
                return
            }
            val req = WXLaunchMiniProgram.Req()
            req.userName = name // 填小程序原始id
            logD("跳转到微信小程序path=$url")
            req.path = url
            req.miniprogramType = miniProgramType
            wxApi.sendReq(req)
        }

        /**
         * 视频链接分享到微信
         * @param scene 0 ->微信对话，1-朋友圈
         */
        @JvmStatic
        fun shareVideoToWx(
            activity:Activity,
            title:String,
            thumbUrl:String,
            videoUrl:String,
            description:String,
            scene: Int = 0,
            onComplete: (() -> Unit)?=null
        ) {
            val video = WXVideoObject()
            video.videoUrl = videoUrl

            val msg = WXMediaMessage(video)


            msg.title = title
            msg.description =description
            val bmp = BitmapFactory.decodeResource(activity.resources, R.mipmap.ic_launcher)
            Glide.with(activity).asBitmap()
                .load(thumbUrl).into(object : SimpleTarget<Bitmap>() {
                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap>?
                    ) {
                        resource.let {
                            val thumbBmp = Bitmap.createScaledBitmap(it, 150, 150, true)
                            bmp.recycle()
                            msg.thumbData = bmpToByteArray(thumbBmp, true)
                            val req = SendMessageToWX.Req()
                            req.transaction = "${System.currentTimeMillis()}"
                            req.message = msg
                            req.scene = scene
                            wxApi.sendReq(req)
                        }
                    }
                })

        }

        /**
         * 图片分享到微信
         * @param scene 0 ->微信对话，1-朋友圈
         */
        @JvmStatic
        fun shareImageToWx(
            bitmap: Bitmap?,
            scene: Int = 0,
            onComplete: () -> Unit
        ) {
            if (bitmap == null) {
                ToastUtils.show("分享失败")
                onComplete.invoke()
                return
            }

            if (!wxApi.isWXAppInstalled) {
                ToastUtils.show("您还没有安装微信客户端哦!")
                onComplete.invoke()
                return
            }
            try {
//                val bmp: Bitmap = changeColor(bitmap)
                //初始化 WXImageObject 和 WXMediaMessage 对象
                val imgObj = WXImageObject(bitmap)
                val msg = WXMediaMessage()
                msg.mediaObject = imgObj

                //设置缩略图
//        int h = (200 * bmp.getHeight()) / bmp.getWidth();
//        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 200, h, true);
//        msg.setThumbImage(thumbBmp);
//        bmp.recycle();
//        msg.thumbData = BitmapUtils.bmpToByteArray(thumbBmp, true);

                //构造一个Req
                val req = SendMessageToWX.Req()
                req.transaction = buildWeixinTransaction("img")
                req.message = msg
                //分享到对话:
                //SendMessageToWX.Req.WXSceneSession
                //分享到朋友圈:
                //SendMessageToWX.Req.WXSceneTimeline ;
                req.scene = scene
                req.userOpenId = WECHAT_APPID_OUR
                //调用api接口，发送数据到微信
                wxApi.sendReq(req)
            } catch (e: java.lang.Exception) {
                ToastUtils.show("分享失败")
            } finally {
                onComplete.invoke()
            }
        }

        private fun buildWeixinTransaction(type: String?): String {
            return if (type == null) System.currentTimeMillis()
                .toString() else type + System.currentTimeMillis()
        }

        /**
         * 微信分享 图片
         */
        fun shareWechatPic(bitmap: Bitmap, scene: Int = SendMessageToWX.Req.WXSceneTimeline) {

            val imgObj = WXImageObject(bitmap)
            val msg = WXMediaMessage()
            msg.mediaObject = imgObj
            val thumbBmp = Bitmap.createScaledBitmap(
                bitmap,
                150,
                (150 * 1.5).toInt(),
                true
            )
            bitmap.recycle()
            msg.thumbData = bmpToByteArray(thumbBmp, true)

            val req = SendMessageToWX.Req()
            req.transaction = CommonUtils.buildTransaction("img")
            req.message = msg
            req.scene = scene
            wxApi.sendReq(req)

        }

        /**
         * 分享图片
         * @param uri
         * @param pkg
         */
        fun shareImageToSystem(context: Context, bitmap: Bitmap?, pkg: String?) {
            try {
                val uri = Uri.parse(
                    MediaStore.Images.Media.insertImage(
                        context.contentResolver,
                        bitmap,
                        "IMG" + System.currentTimeMillis(),
                        null
                    )
                )
                val intent = Intent(Intent.ACTION_SEND)
                intent.type = "image/*"
                intent.putExtra(Intent.EXTRA_STREAM, uri)
                if (!TextUtils.isEmpty(pkg)) intent.setPackage(pkg)
                context.startActivity(Intent.createChooser(intent, "选择分享"))
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}